package boun.center;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;

public class ExamDownloader {
	private String userName, password;
	public ExamDownloader(String userName, String password) {
		this.userName = userName;
		this.password = password;
	}
	
	public ArrayList<Course> fetchCourses() throws Exception {
		HashMap<String, String> data = new HashMap<String, String>();
		data.put("user_name", this.userName);
		data.put("user_pass", this.password);
		return doSubmit("https://registration.boun.edu.tr/scripts/stuinflogin.asp", data);
	}
	
	private ArrayList<Course> doSubmit(String url, HashMap<String, String> data) throws Exception {
		URL siteUrl = new URL(url);
		String charset = "UTF-8";
		URLConnection conn = (HttpsURLConnection) siteUrl.openConnection();

		//conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Accept-Charset", charset);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
		
		Set<String> keys = data.keySet();
		Iterator<String> keyIter = keys.iterator();
		String content = "";
		for(int i=0; keyIter.hasNext(); i++) {
			Object key = keyIter.next();
			if(i != 0) {
				content += "&";
			}
			content += key + "=" + URLEncoder.encode(data.get(key), charset);
		}

		OutputStream output = null;
		try {
		     output = conn.getOutputStream();
		     output.write(content.getBytes(charset));
		} finally {
		     if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
		}
		
		String cookie = "";
		for (Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
			//System.out.println(header.getKey());
			if (header.getKey() != null && header.getKey().toLowerCase().compareTo("set-cookie") == 0) {
				String firstParam = header.getValue().get(0);
				String secondParam = header.getValue().get(1);
				firstParam = firstParam.split(";")[0];
				secondParam = secondParam.split(";")[0];
				cookie = firstParam + "; " + secondParam;
				break;
			}
		}
		URL siteUrl2 = new URL("http://registration.boun.edu.tr/scripts/stuinfsc.asp");
		HttpURLConnection conn2 = (HttpURLConnection) siteUrl2.openConnection();
		conn2.setRequestProperty("Cookie", cookie);
		conn2.setDoInput(true);
		
		BufferedReader in = new BufferedReader(new InputStreamReader(conn2.getInputStream()));
		String line = "";
		StringBuilder sb = new StringBuilder();
		while((line=in.readLine())!=null) {
			//System.out.println(line);
			sb.append(line);
		}
		in.close();
		return parseCourses(sb.toString());
	}
	
	private ArrayList<Course> parseCourses(String content) {
		ArrayList<Course> res = new ArrayList<Course>();
		Pattern rowPattern = Pattern.compile("<tr>(.*?)</tr>"); // Note the use of reluctant quantifier.
		Pattern cellPattern = Pattern.compile("<td.*?>(.*?)</td>");
		Matcher matcher = rowPattern.matcher(content);
		Matcher cellMatcher;
		
		int index = 0;
		while (matcher.find()) {
			if (index > 2) {
				ArrayList<String> cells = new ArrayList<String>();
				String curCourseString = matcher.group(1).trim();
				curCourseString = curCourseString.replaceAll("&nbsp;", "");
				cellMatcher = cellPattern.matcher(curCourseString);
				while (cellMatcher.find()) {
					cells.add(cellMatcher.group(1).trim());
				}
				res.add(createCourse(cells));
			}
			++index;
		}
		return res;
	}
	
	private Course createCourse(ArrayList<String> cells) {
		return new Course(cells.get(0), cells.get(1), cells.get(2), cells.get(3), cells.get(4));
	}
}
